use crate::{
    db::connect_to_db,
    handlers::{get_all_user_posts, get_post, PostGetAllPosts},
    helpers::Bot,
};
use anyhow::Result;

use teloxide::{
    prelude::*,
    types::{InlineKeyboardButton, InlineKeyboardButtonKind, InlineKeyboardMarkup},
};
pub async fn change_page(bot: Bot, q: CallbackQuery, data: &str) -> Result<()> {
    let user_id = q.from.id;
    let user = crate::handlers::get_user(user_id).await?;
    let message_id = q.message.clone().unwrap().id;
    let chat_id = q.message.clone().unwrap().chat.id;
    let pos = data.parse::<i32>()?;
    bot.answer_callback_query(q.id)
        .text(format!("switching to page {}", pos))
        .await?;
    let user_posts = get_all_user_posts(user.id, pos * 50, &db).await?;
    let mut posts = Vec::with_capacity(50);
    for user_post in user_posts {
        let given_post = get_post(&db, user_post.post_id).await?;
        let post = PostGetAllPosts {
            id: given_post.id,
            title: given_post.title,
            url: user_post.original_url,
        };
        posts.push(post);
    }
    let mut button_posts = Vec::with_capacity(51);
    for post in posts {
        let button_name = {
            if let Some(title) = &post.title {
                title
            } else {
                &post.url
            }
        };
        button_posts.push(vec![InlineKeyboardButton::new(
            button_name,
            InlineKeyboardButtonKind::CallbackData(format!(
                "post {} {}",
                post.id.to_hyphenated(),
                pos
            )),
        )]);
    }
    button_posts.push(vec![
        InlineKeyboardButton::new(
            "<-",
            InlineKeyboardButtonKind::CallbackData(format!("page {}", pos - 1)),
        ),
        InlineKeyboardButton::new(
            "->",
            InlineKeyboardButtonKind::CallbackData(format!("page {}", pos + 1)),
        ),
    ]);
    let reply_markup = InlineKeyboardMarkup::new(button_posts);
    bot.edit_message_reply_markup(chat_id, message_id)
        .reply_markup(reply_markup)
        .await?;
    Ok(())
}
